package com.duo.interceptor;

import com.duo.constant.GlobalConstant;
import com.duo.entity.Employee;
import com.duo.enums.errorcode.LoginCode;
import com.duo.exception.BaseException;
import com.duo.utils.JwtUtil;
import com.duo.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果用户没有token
        if (!StringUtils.hasText(token)) {
            log.info("用户未登录");
            throw new BaseException(LoginCode.UN_LOGIN_ERROR);
        }
        // 如果用户有token
        if (JwtUtil.isExpiration(token)) {
            token = JwtUtil.getToken(token);
            Employee admin = redisUtils.getCacheObject(GlobalConstant.ADMIN_TOKEN_PREFIX + token);
            if (!Objects.isNull(admin)) {
                request.setAttribute("admin", admin);
                redisUtils.expire(GlobalConstant.ADMIN_TOKEN_PREFIX + token, GlobalConstant.TIME, TimeUnit.MINUTES);
                return true;
            }
        }
        log.info("用户令牌失效访问, token: {}", token);
        throw new BaseException(LoginCode.ACCESS_TOKEN_ERROR);
    }


}
